/* Global variables */
var day_seeker; //boolean - if we are looking for "today" or not
var position;   //int - which cours we are currently positionned at
var Week;       //String - this weeks number
var Group;      //String - the chosen group
var url;        //String - the compiled url
var nombre_cours_afficher = 1;  //int - how many classes we want to display
var currentTime;                // Date - today's date
var affichageJour;
//onload
//initializes variables required by the config button
function onload(){
	//variables for The config Function
	_currentSide = 0;
	mainView = document.getElementById("mainView");
	configView = document.getElementById("configView");
	frontBottom = document.getElementById("front_bottom");
  backBottom = document.getElementById("back_bottom");
	//set standard size for the widget (defines the size of the widget, same as specified in config.xml - this has higher priority)
	//Also available are :
		// window.resizeBy(xValue, yValue) - resizes the widget window by the values given
		// window.innerWidth - returns the current width of the widget window
		// window.innerHeight - returns the current height of the widget window
	window.resizeTo(400,800);
	//---
	//Add onload load events after this line:
  loadStyle();
  currentTime = new Date();
  Week = getWeek(currentTime);
  position = 0;
  day_seeker = true;
  loadPreference();
  loadGroup()
  fetchXML();	
  opera.postError("URL :"+url);

}
//--------------------Add your code after this line-------------------------
function storeGroup(NewGroup){
                     widget.setPreferenceForKey(""+NewGroup,"Group");
}

function loadGroup(){

  Group = widget.preferenceForKey("Group");
  if (Group==false)
     Group=379;
}

function storePreference(){
         widget.setPreferenceForKey(affichageJour,"affichage");

}

function loadPreference(){
         affichageJour = widget.preferenceForKey("affichage");

          if(affichageJour=="false" || affichageJour=="")
             affichageJour=false;
          else 
             affichageJour=true;          
}


function reload(){
  currentTime = new Date();
  //Week = getWeek(currentTime);
  position = 0;
  day_seeker = true;
  loadPreference();
  loadGroup()
  fetchXML();	
  opera.postError("URL :"+url);
}

  var getWeek=function(date)
  {
    var newYear=new Date(date.getFullYear(), 0,1);
    var correction=1;
    var time=date.getTime();
/* enten denne mÃ¥ten */
/* 
     time-=(((date.getDay()+13)%7)*24*60*60*1000);
      var day=newYear.getDay();
      if(day==0||day==5||day==6) correction=0;
*/

/*   eller denne mÃ¥ten */

      time-=((date.getDay())*24*60*60*1000);

    var weeknumber=Math.ceil((time-newYear.getTime())/(7*24*60*60*1000))+correction;
    if (date.getDay()>5){
    weeknumber++;
    dateIncrease(2);
    }
    //opera.postError(date.getHours());
    if (date.getHours()>=19){
       dateIncrease(1);
    }
    
    if(weeknumber) return weeknumber;
    else return getWeek(new Date(date.getFullYear(), -1, 31));
  }

function fetchXML(){
	try{

    // url  a changer pour qu'il corresponde au serveur tomcat
	  url = "http://10.32.40.223:8080/easyEDT/Groupe"+Group+"Week"+Week+".xml";
	  opera.postError(url);
		xmlhttp=null;
		if(window.XMLHttpRequest){
			xmlhttp=new XMLHttpRequest();
		}else {
			throw 'noReq';
		}
		if(xmlhttp!=null){
			setStatus('XMLHTTP request OK.Loading data...');
			document.getElementById('status').innerHTML='';
			document.getElementById('item').innerHTML= "<div class='cours'><div class='loading' /></div>";
			xmlhttp.onreadystatechange=onResponse;
			xmlhttp.open("GET",url,true);
			xmlhttp.send('');
		}else{
			throw 'noReq';
		}
	}catch(err){
		if(err=='noReq') loadFromCache("Cant't create xml http request.");
		else {
			loadFromCache('Error while fetching data');
		}
	}
}

function onResponse() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			responce=xmlhttp.responseXML.documentElement;
			process(responce);
			setStatus('data loaded');
		} else {
			loadFromCache('Error loading data:'+xmlhttp.statusText+'.Loading from cache');
		}
	}
}
function loadFromCache(msg){
	var cache=widget.preferenceForKey('lastData');
	if(cache.length==0) {
		setStatus('No previous data saved, '+msg);
		return;
	}
	setStatus(msg+'..OK');

}
function process(responce){
    var item = document.getElementById('item');
    var readDate = new Date();
    var readDateString;
    var Class = responce.getElementsByTagName('class').item(0);
    var duration,startTime,endTime,time;
    var nombre_cours = 0;
    var stop = false;
    var cours;
    var buffer="";
    readDate.setFullYear(2000,0,1);
    item.innerHTML = ""; 
    
    if (position < 0)
      position = 0;
    /*This is normally useless */
    if (affichageJour == false)
      nombre_cours_afficher=1;
    /* There are normally no more than 10 classes pr day */
    if (affichageJour == true)
    {
      position=0;
      nombre_cours_afficher=10;
    }
    
    for (var j = 0;j < position;j++){
      Class = Class.nextSibling.nextSibling;
    }
    cours = Class.firstChild;
    /* Loop through the number of classes we want to loop through and while there are more to loop through */
    while((nombre_cours < nombre_cours_afficher) && stop == false){
      buffer="";
      buffer ="<div id='cours"+nombre_cours+"' class='cours "+nombre_cours+"'>";
      /* Loop through a class' childs */
      for( var i =0;i<=12;i++){
        if (cours.firstChild != null){
          if(cours.tagName=='date'){
            readDateString = cours.firstChild.text.split(/\//);
            readDate.setFullYear(readDateString[2],readDateString[1]-1,readDateString[0]);
            buffer =buffer +"<div id=\'"+cours.tagName+nombre_cours+"' class=\'"+cours.tagName +" "+nombre_cours+"'>"+cours.firstChild.text+"</div>";
          }
          else{
            if (cours.tagName=='duration')
            {
              duration = cours.firstChild.text.split(/h/);
            }
            else{
              if (cours.tagName=='time')
              {
                readDateString = cours.firstChild.text.split(/h/);
                readDate.setHours(readDateString[0]);
                startTime= cours.firstChild.text.split(/h/);
                buffer =buffer +"<div id='time"+nombre_cours+"' class=\'" +cours.tagName +"'>"+cours.firstChild.text+"</div>";
              }
              else{
                  buffer =buffer +"<div id=\'"+cours.tagName+nombre_cours+"' class=\'"+cours.tagName +" "+nombre_cours+"'>"+cours.firstChild.text+"</div>";
              }
            }
          }
        }
        cours = cours.nextSibling;
  		}
  		//opera.postError(readDate + "     -"+nombre_cours_afficher+"  "+nombre_cours);
      if(readDate<currentTime && day_seeker)
      {
        nombre_cours=0;
        buffer="";
        position++;
        
      }
      else{
            if(readDate.getDay()>currentTime.getDay())
            {
             stop = true;
             //document.getElementById('cours'+nombre_cours).style.display='none';
            }
             if ((stop != true) || (nombre_cours < 1)){
             buffer =buffer +"</div>";
             item.innerHTML += buffer;
             buffer="";
             endTime = parseInt(startTime[0])+parseInt(duration[0]);
          		if ((parseInt(startTime[1])+parseInt(duration[1]))>=60){
                 endTime = parseInt(endTime)+1;
                 endTime=  endTime +"h" +(parseInt((parseInt(startTime[1])+parseInt(duration[1]))) - 60);
              }
              else
              {
                  endTime = endTime +"h" +(parseInt(startTime[1])+parseInt(duration[1]));
              }
              time = document.getElementById('time'+nombre_cours);
              time.innerHTML = time.innerHTML + " - " +endTime;
              
              document.getElementById('status').innerHTML = document.getElementById('date0').innerHTML;
              }
              nombre_cours++;
      }
		  
      if (Class.nextSibling.nextSibling != null){
         Class = Class.nextSibling.nextSibling;
         cours = Class.firstChild;
      }
      else{
      stop = true;
      }
    }      
    //opera.postError(document.getElementById('item').innerHTML);
    
    day_seeker=false;
     
}

function setStatus(msg){
	document.getElementById('status').innerHTML=msg;
	opera.postError(msg);
	if (document.getElementById('date0')!=null)
    document.getElementById('status').innerHTML = document.getElementById('date0').innerHTML;
  else 
       document.getElementById('status').innerHTML = "Vacances!";
}


function dateIncrease(k){
    currentTime.setDate(currentTime.getDate()+k);
    currentTime.setHours(7);
    day_seeker=true;
    
    if(currentTime.getDay()>5){
      Week++;
      document.getElementById('item').innerHTML= "<div class='cours'><div class='loading' /></div>";
      reload();
    }
}



function saveStyle(style){

  if (style!=""){
    widget.setPreferenceForKey(style,"Style");
    var ele=document.getElementById('style');
        if(ele) ele.parentNode.removeChild(ele);
    ele=document.getElementsByTagName('head')[0].
    appendChild(document.createElement('link'));
    ele.rel='stylesheet';
    ele.id='style';
    ele.href='css/'+style+'.css';
    reload();
  }
}

function loadStyle(){
    var style = widget.preferenceForKey("Style");
    if (style!=""){
      var ele=document.getElementById('style');
          if(ele) ele.parentNode.removeChild(ele);
      ele=document.getElementsByTagName('head')[0].
      appendChild(document.createElement('link'));
      ele.rel='stylesheet';
      ele.id='style';
      ele.href='css/'+style+'.css';
    }
}




//----------------------do not edit below this line----------------------------
//The Toggle Function to show the config and main views of the widget
function toggleSide(){
	if(_currentSide == 0){
		if (window.widget)
        	widget.prepareForTransition("ToFront");
		frontBottom.style.display = "none";
	    backBottom.style.display = "block";
	    mainView.style.display = "none";
		configView.style.display = "block";
		_currentSide = 1;
		 if (window.widget)
	        setTimeout ('widget.performTransition();', 0);
		
	} else {
	if (window.widget)
        	widget.prepareForTransition("ToBack");
		mainView.style.display = "block";
		configView.style.display = "none";
		frontBottom.style.display = "block";
	    backBottom.style.display = "none";
		_currentSide = 0;
		 if (window.widget)
	        setTimeout ('widget.performTransition();', 0);
	}
}
